package com.solo.eggsolo.config;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
 * 
 * @author Yu
 *
 */
@Configuration
@EnableSwagger2

public class SwaggerConfig {

	@Bean
	public Docket UserApiConFig() {
		// 分组1
		return new Docket(DocumentationType.SWAGGER_2).groupName("UserApi")
				.apiInfo(UserApiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage("com.solo.eggsolo.controller")).paths(PathSelectors.any())
				.build().securitySchemes(security()).securityContexts(securityContexts());
	}

	private List<ApiKey> security() {
		return Collections.singletonList(new ApiKey("Authorization", "Authorization", "header"));
	}

	/**
	 * 设置认证规则
	 */
	private List<SecurityContext> securityContexts() {
		List<String> antPaths = new ArrayList<>(Arrays.asList("/auth/**"));
		return Collections.singletonList(SecurityContext.builder().securityReferences(defaultAuth())
				.forPaths(antPathsCondition(antPaths)).build());
	}

	/**
	 * 返回认证路径的条件
	 */
	private Predicate<String> antPathsCondition(List<String> antPaths) {
		List<Predicate<String>> list = new ArrayList<>();
		antPaths.forEach(path -> list.add(PathSelectors.ant(path)));
		return Predicates.or(list);
	}

	/**
	 * 设置认证的范围，以及认证的字段名称
	 */
	private List<SecurityReference> defaultAuth() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		return Collections.singletonList(new SecurityReference("Authorization", authorizationScopes));
	}
	/**
	 * 配置用户文档信息
	 */
	private ApiInfo UserApiInfo() {
		 // 标题
		return new ApiInfoBuilder().title("皮蛋solo粥")
				 // 描述
				.description("swagger")
				 // 版本
				.version("1.0")
				 // 联系人信息
				.contact(new Contact("yu", "https://gitee.com/yushi-lu", "yushi_Lu@163.com"))
				.build();
	}

}
